package com.sx.basic;

import com.sx.basic.exception.BasicException;
import com.sx.redis.service.RedisService;
import com.sx.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author AdinZ
 * @date 2020/11/7 17:08
 */
@Service @Slf4j
public class TokenService {
    @Resource private RedisService redisService;

    /**
     * 获取token资料
     * @param token
     * @param <T>
     * @return
     */
    public <T>TokenEntity<T> getToken(String token){
        if(StringUtils.isEmpty(token)){
            throw new BasicException(ResponseEntity.CODE_TOKEN_FAIL,"token 不能空");
        }
        String key = this.redisService.get(token);
        if(StringUtils.isEmpty(key))throw new BasicException(ResponseEntity.CODE_TOKEN_FAIL,"token过期");
        TokenEntity entity= this.redisService.get(TokenEntity.TOKEN_VALUE, key);
        if(entity==null)throw new BasicException(ResponseEntity.CODE_TOKEN_FAIL,"token不存在");
        if(entity.getExpire()<System.currentTimeMillis()){
            this.deleteToken(token);
            throw new BasicException(ResponseEntity.CODE_TOKEN_FAIL,"登陆超时,请重新登陆");
        }
        if(entity.getType()== TokenEntity.Type.SYSTEM){
            entity.setExpire(DateUtils.addHour(1).getTime());
            this.redisService.set(TokenEntity.TOKEN_VALUE, key, entity);
        }
        return entity;
    }

    /**
     * 生成token
     * @param tokenEntity
     */
    public void tokenGen(TokenEntity tokenEntity) {
        String key = tokenEntity.getUid()+"_"+tokenEntity.getType() + "_" + tokenEntity.getChannel();
        Set<String> keys = this.redisService.keys(tokenEntity.getTokenStart() + "*");
        if(keys!=null||keys.size()>0) {
            keys.forEach(k -> {
                String r = this.redisService.get(k);
                this.redisService.delete(k);
                this.redisService.delete(TokenEntity.TOKEN_VALUE, r);
            });
        }
        this.redisService.set(tokenEntity.getToken(), key, tokenEntity.getExpire());
        this.redisService.set(TokenEntity.TOKEN_VALUE, key, tokenEntity);
    }

    /**
     * 获取token 绑定uid
     * @param token
     * @return
     */
    public long getUid(String token){
        TokenEntity tokenEntity = this.getToken(token);
        if(tokenEntity==null)throw new BasicException(ResponseEntity.CODE_TOKEN_FAIL,"token失效或不存在");
        return tokenEntity.getUid();
    }

    /**
     *
     * @param token
     */
    public void deleteToken(String token){
        String key = this.redisService.get(token);
        if(StringUtils.isEmpty(key))return;
        this.redisService.delete(token);
        this.redisService.delete(TokenEntity.TOKEN_VALUE, key);
    }




}
